﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Toolbox.Converters
{
    public static class Extenders
    {
        public static object ParseTo(this object value, Type type)
        {
            string str = value.ToString();

            if (type.IsArray)
            {
                return str.Split(new char[] {str[0]},StringSplitOptions.RemoveEmptyEntries).ParseTo(type);
            }
            else
            {
                if (type == typeof(TimeSpan))
                {
                    return TimeSpan.Parse(str);
                }
                else
                {
                    return Convert.ChangeType(value, type, CultureInfo.CurrentCulture);
                }
            }
        }

        internal static Array ParseTo(this object[] value, Type type)
        {
            if (!type.IsArray)
            {
                throw new ArgumentException("Not an array");
            }

            Type eType = type.GetElementType();

            var obj = value.Select(s => s.ParseTo(eType)).ToArray();
            var arr = Array.CreateInstance(eType, value.Length);
            Array.Copy(obj, arr, value.Length);

            return arr;
        }
    }
}
